/**
 * 
 */
package com.nari.basic.dao;

import com.nari.basic.model.IUserRole;
import com.nari.coreframe.dao.hibernate3.GenericDaoImpl;
import com.nari.platform.utils.StringUtils;

/**
 * 
 * @author Xiaopeng
 * @date 2013-7-18
 */
public class UserRoleDaoImpl extends GenericDaoImpl<IUserRole, String> 
		implements IUserRoleDao {

	/**
	 * 通过用户唯一标识删除用户角色关联信息
	 * @param userUID
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-7-25
	 */
	public void deleteByUserUID(String userUID) throws Exception {
		String hsql = "delete from IUserRole ur " +
				"where ur.userUuid='"+userUID+"'";
		this.runFormatHSql(hsql);
	}
	
	/**
	 * 通过角色唯一标识删除用户角色关联信息
	 * @param roleUID
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-7-26
	 */
	public void deleteByRoleUID(String roleUID) throws Exception {
		String hsql = "delete from IUserRole ur " +
				"where ur.roleUuid='"+roleUID+"'";
		this.runFormatHSql(hsql);
	}
	
	/**
	 * 新增用户角色授权信息
	 * @param roleUID 角色唯一标识列表
	 * @param userUIDList 用户唯一标识列表
	 * 	格式：XXX,XXX,XXX
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-7-29
	 */
	public void saveUserRoleAuthority(String roleUID, String userUIDList) throws Exception {
		String[] userUIDs = userUIDList.split("[,]");
		for(String userUID: userUIDs) {
			IUserRole userRole = new IUserRole();
			userRole.setUserUuid(userUID);
			userRole.setRoleUuid(roleUID);
			this.saveEntity(userRole);
		}
	}
	
	/**
	 * 删除用户角色授权信息
	 * @param roleUID 角色唯一标识列表
	 * @param userUIDList 用户唯一标识列表
	 * 	格式：XXX,XXX,XXX
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-7-29
	 */
	public void deleteUserRoleAuthority(String roleUID, String userUIDList) throws Exception {
		String userUIDFormat = StringUtils.formatIDListWithSyntax(userUIDList, ",", "'");
		String hsql = "delete from IUserRole ur " +
				"where ur.roleUuid='"+roleUID+"' " +
				"and ur.userUuid in("+userUIDFormat+")";
		this.runFormatHSql(hsql);
	}
	
	/**
	 * 统计用户ID和角色ID同时存在的条目数
	 * @param userUID
	 * @param roleUID
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-1-12
	 */
	public int countByUserUIDAndRoleUID(String userUID, String roleUID) throws Exception {
		String hsql = "select count(*) " +
				"from IUserRole ur " +
				"where ur.userUuid='"+userUID+"' " +
				"and ur.roleUuid='"+roleUID+"'";
		return ((Long)this.getCurrentSession().createQuery(hsql).uniqueResult()).intValue();
	}
}
